package compare;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 定制排序  Comparator
 */
public class ComparatorTest {
    @Test
    public void test1() {
        Product[] products = new Product[5];

        products[0] = new Product("Xiaomi", 3289);
        products[1] = new Product("Huawei", 5699);
        products[2] = new Product("iPhone", 8099);
        products[3] = new Product("HuaweiMate50", 5699);
        products[4] = new Product("OPPO", 3699);

        // 创建一个实现了Comparator接口的实现类的对象
        Comparator comparator = new Comparator() {
            // 判断标准
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Product p1 && o2 instanceof Product p2) {
                    int value = p1.getName().compareToIgnoreCase(p2.getName());
                    return value == 0 ? (int) (p1.getPrice() - p2.getPrice()) : value;
                }
                throw new RuntimeException("类型不匹配");
            }
        };
        Arrays.sort(products, comparator);

        for (int i = 0; i < 5; i++) {
            System.out.println(products[i]);
        }
//        System.err.println("你好");
    }

}
